package com.company.cloud.product.modules.mgr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.log.annotation.SysLog;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.product.constant.ProductErrorEnum;
import com.company.cloud.product.modules.api.response.ProductCategoryModel;
import com.company.cloud.product.modules.base.entity.CategoryInfo;
import com.company.cloud.product.modules.base.entity.ProductInfo;
import com.company.cloud.product.modules.base.service.CategoryInfoService;
import com.company.cloud.product.modules.base.service.ProductInfoService;
import com.company.cloud.product.modules.cache.service.ProductConfigCacheService;
import com.company.cloud.product.modules.mgr.controller.req.CategoryInfoSaveParam;
import com.company.cloud.product.modules.mgr.controller.req.CategoryInfoTreeParam;
import com.company.cloud.product.modules.mgr.controller.req.CategoryInfoUpdateParam;
import com.company.common.server.config.cloud.ProjectConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类管理
 */
@Authc
@RestController
@RequestMapping("/mgr/prd/category")
@Api(tags = "Product_Mgr_商品分类管理")
public class CategoryMgrController {

    @Autowired
    private CategoryInfoService categoryInfoService;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductConfigCacheService productConfigCacheService;

    @Autowired
    private ProjectConfig projectConfig;

    @GetMapping("/tree")
    @SysLog("商品分类树")
    @ApiOperation(value = "商品分类树", response = BaseResult.class)
    public BaseResult query(CategoryInfoTreeParam params) {
        String companyNo = null;
        if (projectConfig.isPlatformPattern()) {
            if (params != null && CheckUtils.hasText(params.getCompanyNo())) {
                companyNo = params.getCompanyNo();
            }
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (StringUtils.isEmpty(companyNo)) {
            companyNo = userInfo.getCompanyNo();
        }

        List<ProductCategoryModel> data = productConfigCacheService.getProductCategorysByCache(companyNo);
        List<ProductCategoryModel> result = new ArrayList<>();
        for (ProductCategoryModel model : data) {
            if (model.getParentId() == 0) {
                model.setChildren(this.getChildren(data, model.getId()));
                result.add(model);
            }
        }

        return BaseResult.ok(result);
    }

    private List<ProductCategoryModel> getChildren(List<ProductCategoryModel> data, int parendId) {
        List<ProductCategoryModel> returnList = new ArrayList<>();
        for (ProductCategoryModel model : data) {
            if (model.getParentId() == parendId) {
                model.setChildren(this.getChildren(data, model.getId()));
                returnList.add(model);
            }
        }
        return returnList;
    }

    @GetMapping("/get")
    @SysLog("商品分类表详情")
    @ApiOperation(value = "商品分类表详情查询")
    public BaseResult get(@RequestParam("id") Integer id) {
        ProductCategoryModel data = productConfigCacheService.getProductCategoryByIdByDB(id);
        return BaseResult.ok(data);
    }

    @PostMapping("/save")
    @SysLog("商品分类表新增")
    @ApiOperation(value = "商品分类表新增")
    @StaffLogc(title = "商品分类新增", action = "商品分类新增", actionAdo = "商品分类")
    public BaseResult save(@RequestBody CategoryInfoSaveParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        CategoryInfo parentEntity = null;
        if (params.getParentId() != 0) {
            parentEntity = categoryInfoService.getById(params.getParentId());
            if (parentEntity == null) {
                throw new BusinessException(ProductErrorEnum.ProductCategory_Parent_NotExist);
            }
        }
        CategoryInfo entity = new CategoryInfo();
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setLangType(AuthContextUtils.getLang());
        entity.setName(params.getName());
        entity.setImg(params.getImg());
        entity.setOrders(params.getOrders());
        entity.setInstructions(params.getInstructions());
        entity.setRemark(params.getRemark());
        entity.setParentId(params.getParentId());
        entity.setConfigId(params.getConfigId());
        if (parentEntity == null) {
            entity.setGrade(0);
            entity.setTreePath(",");
        }
        entity.addCreateParam(userInfo);
        categoryInfoService.save(entity);

        if (parentEntity != null) {
            /* entity.setGrade(parentEntity.getGrade() + 1);*/
            entity.setGrade(params.getGrade());
            entity.setTreePath(parentEntity.getTreePath() + entity.getId().toString() + ",");
            categoryInfoService.updateById(entity);
        } else {
            entity.setGrade(params.getGrade());
            entity.setTreePath("," + entity.getId().toString() + ",");
            categoryInfoService.updateById(entity);
        }
        productConfigCacheService.removeProductCategoryByCache(entity.getCompanyNo());
        return BaseResult.ok();
    }

    @PostMapping("/update")
    @SysLog("商品分类表修改")
    @ApiOperation(value = "商品分类表修改")
    @StaffLogc(title = "商品分类修改", action = "商品分类修改", actionAdo = "商品分类")
    public BaseResult update(@RequestBody CategoryInfoUpdateParam params) {
        CategoryInfo entity = categoryInfoService.getById(params.getId());
        if (entity == null) {
            throw new BusinessException(ProductErrorEnum.ProductCategory_NULL);
        }

        String treePath = params.getTreePath();

        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setName(params.getName());
        entity.setImg(params.getImg());
        entity.setOrders(params.getOrders());
        entity.setRemark(params.getRemark());
        entity.setConfigId(params.getConfigId());
        entity.setGrade(params.getGrade());
        entity.setInstructions(params.getInstructions());
        entity.addEditParam(userInfo);
        entity.setParentId(params.getParentId());
        entity.setTreePath(treePath);
        categoryInfoService.updateById(entity);
        productConfigCacheService.removeProductCategoryByCache(entity.getCompanyNo());

        List<ProductInfo> productInfoList = productInfoService
                .list(new QueryWrapper<ProductInfo>().eq("category_id", entity.getId()));
        for (ProductInfo productInfo : productInfoList) {
            Integer categoryId = productInfo.getCategoryId();
            if (categoryId != null) {
                CategoryInfo category = categoryInfoService.getById(categoryId);
                if (category != null && category.getTreePath() != null) {
                    productInfo.setTreePath(category.getTreePath());
                    productInfoService.updateById(productInfo);
                }
            }
        }

        return BaseResult.ok();
    }

    @GetMapping("/delete")
    @SysLog("商品分类表删除")
    @ApiOperation(value = "商品分类表删除")
    @StaffLogc(title = "商品分类删除", action = "商品分类删除", actionAdo = "商品分类")
    public BaseResult delete(@RequestParam("id") Integer id) {
        CategoryInfo entity = categoryInfoService.getById(id);
        if (entity == null) {
            throw new BusinessException(ProductErrorEnum.ProductCategory_NULL);
        }
        int count = categoryInfoService.count(new QueryWrapper<CategoryInfo>().eq("parent_id", id));
        if (count > 0) {
            throw new BusinessException(ProductErrorEnum.ProductCategory_Children_Exist);
        }
        int productCount = productInfoService.count(new QueryWrapper<ProductInfo>().eq("category_id", id));
        if (productCount > 0) {
            throw new BusinessException(ProductErrorEnum.ProductCategory_Product_Exist);
        }
        categoryInfoService.removeById(id);
        productConfigCacheService.removeProductCategoryByCache(entity.getCompanyNo());
        return BaseResult.ok();
    }
}
